import facade
from xjlibrary.our_file_dir import BaseDir
from xjlibrary.our_file_dir import ImageFile

curpath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curpath, -2)
dirPath = BaseDir.get_new_path(TopPath, "download", "yuetongbook", "download", "cover")
BaseDir.create_dir(dirPath)
configfile = BaseDir.get_new_path(curpath, "db.ini")


class DownCover(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(configfile, "db", logger=self.logger)

    def select_cover(self):
        sql = "select rawid,coverurl from book where coverstat=0"
        rows = self.mysqlutils.SelectFromDB(sql)
        for row in rows:
            name = row[0].lower() + ".jpg"
            coverpath = BaseDir.get_new_path(dirPath, name)
            if BaseDir.is_file_exists(coverpath):
                self.logger.info(name + "文件存在")
                sql = "update book set coverstat=1 where rawid='{}'".format(row[0])
                self.mysqlutils.ExeSqlToDB(sql)
                continue
            url = "http://zt.yuetong.cn" + row[1]
            if self.down_cover(url, row[0]):
                sql = "update book set coverstat=1 where rawid='{}'".format(row[0])
                self.mysqlutils.ExeSqlToDB(sql)

    def down_cover(self, url, rawid):
        BoolResult, errString, r = facade.BaseRequest(url,
                                                      endstring="",
                                                      timeout=(30, 60))
        if BoolResult:
            return self.save_file(rawid, r.content)
        else:
            self.logger.info("图片下载失败")
            return False

    def save_file(self, rawid, content):
        name = rawid.lower() + ".jpg"
        if ImageFile.img_to_format_jpg(content, BaseDir.get_new_path(dirPath, name)):
            self.logger.info("图片保存成功")
            return True
        return False


if __name__ == "__main__":
    down = DownCover()
    down.select_cover()
